package com.heihei.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heihei.domain.User;
import com.heihei.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    ObjectMapper objectMapper = new ObjectMapper();

    //登录功能
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestBody User user, HttpSession session){
        String s = "No";
        //登录成功就返回用户User信息，登录失败就返回字符串：  No
        if(user != null || user.getUsername() != null && user.getUsername().length() > 0 && user.getPassword() != null && user.getPassword().length() > 0) {
            User loginUser = userService.login(user.getUsername(), user.getPassword());
            if(loginUser != null) {
                //用户名密码正确，成功查询出用户信息
                loginUser.setPassword(null);

                //将用户信息存入到session域中，说明登录状态为 已登录
                session.setAttribute("currentUser", loginUser);

                try {
                    s = objectMapper.writeValueAsString(loginUser);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }
        //用户名密码错误或者为空，则返回No;
        //登陆成功，s就是 用户信息
        return s;
    }

    //刷新页面时，查看session中是否已有登录信息
    @RequestMapping("/isLogin")
    @ResponseBody
    public String login(HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        String str = null;
        //不为空，表示已登录，str设置为user的JSON字符串
        if (currentUser != null){
            try {
                str = objectMapper.writeValueAsString(currentUser);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    //退出登录
    @RequestMapping("/logOut")
    @ResponseBody
    public String logOut(HttpSession session) {
        session.removeAttribute("currentUser");

        return "OK";
    }

}
